from rest_framework import serializers
from decimal import Decimal
import logging, json, datetime, requests, time
from django_redis import get_redis_connection
from django.db.models import Q, F, Max, Sum

from merchants.models import *
from goods.models import *
from orders.models import *
from equity_mall.utils.express_utils import KuaiDi100
from vouchers.models import *
from equity_mall.utils.sync_img_to_local import make_qrcode
from merchants.utils import create_contract_table

logger = logging.getLogger('django')


class MerchantInfoModelSerializer(serializers.ModelSerializer):

    subject_type_str = serializers.CharField(source='get_subject_type_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_mall_str = serializers.CharField(source='get_is_mall_display', read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'wyfMerchantID', 'name', 'subject_type', 'subject_type_str', 'managerName', 'managermobile', 'create_time', 'is_mall', 'is_mall_str']


class MerchantImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantImage
        fields = ['id', 'image']


class MerchantModelSerializer(serializers.ModelSerializer):

    is_online_str = serializers.CharField(source='get_is_online_display', read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    business_category_name = serializers.SerializerMethodField(read_only=True)
    open_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    close_work_time = serializers.DateTimeField(format="%H:%M", required=False)
    merchantimage_set = MerchantImageSerializer(many=True)
    provincial_code = serializers.SerializerMethodField(read_only=True)
    region = serializers.SerializerMethodField(read_only=True)
    coupon_set = serializers.SerializerMethodField(read_only=True)
    merchant_home_qrcode = serializers.SerializerMethodField(read_only=True)
    is_mall = serializers.SerializerMethodField(read_only=True)
    is_mall_str = serializers.SerializerMethodField(read_only=True)
    contract_table = serializers.SerializerMethodField(read_only=True)
    information = serializers.SerializerMethodField(read_only=True)
    service_token = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Merchant
        fields = ['id', 'is_online', 'is_online_str', 'name', 'short_name', 'managerName', 'wyfMerchantID', 'level_name',
                  'merchant_desc', 'business_category_name', 'business_category_id', 'close_work_time', 'open_work_time',
                  'store_logo_copy', 'merchantimage_set', 'managermobile', 'prov_name', 'city_name', 'district_name', 'store_address',
                  'longitude', 'latitude', 'region', 'provincial_code', 'coupon_set', 'merchant_home_qrcode', 'is_mall', 'is_mall_str',
                  'contract_table', 'information', 'service_token']

    def get_service_token(self, obj):
        try:
            redis_conn = get_redis_connection("session")
            service_token_server = redis_conn.get("token_%s" % obj.wyfMerchantID)
            if not service_token_server:
                url = 'https://ai.infly.com.cn/external/wyh/login/'
                body = {"openid": obj.wyfMerchantID}
                response = requests.post(url=url, data=body)
                result = response.json()
                service_token_server = result['token']
                redis_conn.setex("token_%s" % obj.wyfMerchantID, result['exp']-int(time.time()), service_token_server)
            else:
                service_token_server = service_token_server.decode()
            return service_token_server
        except:
            return ''

    def get_information(self, obj):
        data = {}
        data['applyment_type_str'] = ''
        data['applyment_type'] = ''
        data['context'] = ''
        data['create_time'] = ''
        data['applyment_state'] = ''
        data['applyment_state_str'] = ''
        data['contract'] = ''
        data['verify_time'] = ''
        data['verify_user'] = ''
        data['audit_time'] = ''
        try:
            instance = MerchantMallApplyment.objects.filter(applyment_state__in=[1, 3, 2], merchant_id=obj.id).last()
            if instance:
                data['applyment_type_str'] = instance.get_applyment_type_display()
                data['applyment_type'] = instance.applyment_type
                data['context'] = instance.context
                data['create_time'] = instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                data['verify_user'] = instance.verify_user.username
                data['applyment_state'] = instance.applyment_state
                data['applyment_state_str'] = instance.get_applyment_state_display()
                data['verify_time'] = instance.verify_time.strftime('%Y-%m-%d %H:%M:%S')
                data['audit_time'] = instance.audit_time.strftime('%Y-%m-%d %H:%M:%S')
                try:
                    data['contract'] = instance.contract.url
                except:
                    data['contract'] = ''
        except:
            pass
        return data

    def get_contract_table(self, obj):
        try:
            if obj.subject_type != 1:
                if not obj.contract_table:
                    url = 'https://manage.gdwxyf.com/internal/searchmerchantbyshopids.do'
                    body = {
                        'shopId': obj.ruiyinxinMerchantID,
                        'account': 'gdyouzheng'
                    }
                    response = requests.post(url=url, data=body)
                    result = response.json()
                    merchant_name = result['shopName']
                    merchant_other_5 = result['allchannelJson']['channel_sxf_tq']['merchant_other_5']
                    artifIdentity = result['artifIdentity']
                    licenceNo = result['licenceNo']
                    contract_table = create_contract_table(merchant_name, merchant_other_5, artifIdentity, licenceNo)
                    obj.contract_table = contract_table
                    obj.save()
                    return f'https://circle.sutpay.cn/{contract_table}'
                else:
                    return obj.contract_table.url
            else:
                return ''
        except Exception as e:
            print(e)
            return ''

    def get_is_mall(self, obj):
        try:
            if not obj.is_mall:
                return 0
            else:
                return obj.is_mall
        except:
            return 1

    def get_is_mall_str(self, obj):
        try:
            if not obj.is_mall:
                return '未上架'
            else:
                return obj.get_is_mall_display()
        except:
            return '未上架'

    def get_merchant_home_qrcode(self, obj):
        try:
            if not obj.merchant_home_url:
                merchant_home_url = f'https://api.sutpay.com/customer/merchant_home/?id={obj.id}'
                merchant_home_qrcode = f'youhuiquanyi/{obj.wyfMerchantID}/merchant_home.png'
                common_qrcode_url = make_qrcode(obj.wyfMerchantID, merchant_home_url, merchant_home_qrcode)
                obj.merchant_home_qrcode = merchant_home_qrcode
                obj.merchant_home_url = merchant_home_url
                obj.save()
                return f'https://circle.sutpay.cn/{merchant_home_qrcode}'
            else:
                return obj.merchant_home_qrcode.url
        except:
            return ''

    def get_coupon_set(self, obj):
        return []

    def get_provincial_code(self, obj):
        data = []
        try:
            if obj.prov_code:
                data.append(obj.prov_code)
                data.append(obj.city_code)
                data.append(obj.district_code)
        except:
            pass
        return data

    def get_region(self, obj):
        data = []
        try:
            if obj.prov_name:
                data.append(obj.prov_name)
                data.append(obj.city_name)
                data.append(obj.district_name)
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except Exception as e:
            return ''

    def get_business_category_name(self, obj):
        try:
            return obj.business_category.name
        except Exception as e:
            return ''


class MerchantInfoChoicesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Merchant
        fields = ['id', 'wyfMerchantID', 'name']


class MerchantUserInfoModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    auth_state_str = serializers.CharField(source='get_auth_state_display', read_only=True)
    merchant_set = MerchantInfoChoicesSerializer(many=True)

    class Meta:
        model = MerchantUser
        fields = ['id', 'mobile', 'create_time', 'nickName', 'auth_state', 'auth_state_str', 'merchant_set']

    def get_merchantinfo_set(self, obj):
        try:
            merchantinfo_set = Merchant.objects.filter(merchant_user_id=obj.id)
            return MerchantInfoChoicesSerializer(merchantinfo_set, many=True).data
        except:
            return []


class OrderGoodsSerializer(serializers.ModelSerializer):

    default_image = serializers.SerializerMethodField(read_only=True)
    name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ('id', 'default_image', 'count', 'name', 'price')

    def get_default_image(self, obj):
        try:
            return obj.goods.default_image.url
        except Exception as e:
            return ''

    def get_name(self, obj):
        try:
            return obj.goods.name
        except Exception as e:
            return ''


class OrderInfoListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    customer_user_mobile = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state', 'state_str', 'ordergoods_set', 'total_point', 'use_time', 'total_price', 'level_name',
                  'customer_user_mobile', 'orderNum', 'order_species', 'order_species_str', 'freight', 'payment_time']

    def get_customer_user_mobile(self, obj):
        try:
            return obj.customer_user.mobile
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return f'{obj.level.name}(分店)'
        except:
            return '总店'


class GoodsCouponsModelSerializer(serializers.ModelSerializer):

    status_str = serializers.CharField(source='get_status_display', read_only=True)
    coupons_id = serializers.SerializerMethodField(read_only=True)
    validity_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = GoodsCoupons
        fields = ['id', 'status_str', 'status', 'coupons_id', 'validity_time']

    def get_coupons_id(self, obj):
        if obj.status == 1:
            return obj.coupons_id[:8] + '********'
        else:
            return obj.coupons_id


class OrderAddressModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderAddress
        fields = ['id', 'receiver', 'place', 'mobile', 'province', 'city', 'district']


class ExpressPlanModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    class Meta:
        model = ExpressPlan
        fields = ('id', 'create_time', 'remark')


class ExpressModelSerializer(serializers.ModelSerializer):

    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    express_name = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    expressplan_set = serializers.SerializerMethodField(read_only=True)
    deliverystatus = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'deliverystatus', 'deliverystatus_str', 'express_number', 'express_name', 'create_time', 'expressplan_set')

    def get_deliverystatus(self, obj):
        try:
            if obj.deliverystatus in [0, 1, 5, 2, 6]:
                redis_conn = get_redis_connection("express_number")
                express_number_flag = redis_conn.get("express_number_%s" % obj.express_number)
                if not express_number_flag:
                    redis_conn.setex('express_number_%s' % obj.express_number, 21600, 1)
                    order = ExpressOrderRelevance.objects.filter(express_id=obj.id).first()
                    phone = OrderAddress.objects.filter(order_id=order.order_id).first()
                    if phone:
                        result = KuaiDi100().track(obj.express_type.express_type, obj.express_number, phone.mobile[-4:])
                    else:
                        result = KuaiDi100().track(obj.express_type.express_type, obj.express_number)
                    if result['status'] == '200':
                        obj.deliverystatus = result['state']
                        obj.save()
                        if obj.deliverystatus == 3:
                            try:
                                order = obj.order
                                user = order.user
                            except:
                                pass
                        for i in result['data']:
                            plan_data = {}
                            plan_data['express_id'] = obj.id
                            plan_data['create_time'] = i['time']
                            plan_data['remark'] = i['context']
                            ExpressPlan.objects.get_or_create(defaults=plan_data, create_time=i['time'], express_id=obj.id)
                        if str(obj.deliverystatus) == "3":
                            try:
                                sign_time = ExpressPlan.objects.filter(express_id=obj.id).aggregate(Max('create_time'))['create_time__max']
                                obj.sign_time = sign_time
                                obj.save()
                            except:
                                pass
                    else:
                        obj.deliverystatus = 9
                        obj.save()
                        ExpressPlan.objects.create(remark=result['message'], create_time=datetime.datetime.now(), express_id=obj.id)
            return obj.deliverystatus
        except:
            return obj.deliverystatus

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_name(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''


class AfterSaleApplicationFormModelSerializer(serializers.ModelSerializer):

    form_status_str = serializers.CharField(source='get_form_status_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    img_array = serializers.SerializerMethodField(read_only=True)
    reason = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AfterSaleApplicationForm
        fields = ['id', 'form_status', 'form_status_str', 'create_time', 'description', 'refund_money', 'return_msg',
                  'refund_time', 'reason', 'img_array', 'application_num']


class OrderFundTransModelSerializer(serializers.ModelSerializer):

    trans_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    status_str = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = OrderFundTrans
        fields = ['id', 'trans_date', 'exchange_amount', 'status', 'status_str', 'identity', 'name', 'pay_fund_order_id', 'sub_msg']


class RefundOrderInfoModelSerializer(serializers.ModelSerializer):

    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    user = serializers.SerializerMethodField(read_only=True)
    refund_status_str = serializers.CharField(source='get_refund_status_display', read_only=True)
    refund_type_str = serializers.CharField(source='get_refund_type_display', read_only=True)
    operator_role_str = serializers.CharField(source='get_operator_role_display', read_only=True)

    class Meta:
        model = RefundOrderInfo
        fields = ['id', 'refund_time', 'user', 'refund_order_id', 'refund_transaction_id', 'refund_money', 'refund_procedure_money', 'refund_status',
                  'refund_status_str', 'return_msg', 'refund_type', 'refund_type_str', 'operator_role', 'operator_role_str', 'remark']

    def get_user(self, obj):
        try:
            user = obj.user
            return user.nickname
        except Exception as e:
            return ''


class OrderInfoRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    use_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    payment_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    state_str = serializers.CharField(source='get_state_display', read_only=True)
    ordergoods_set = OrderGoodsSerializer(many=True)
    customer_user = serializers.SerializerMethodField(read_only=True)
    companyuser = serializers.SerializerMethodField(read_only=True)
    orderfundtrans_set = OrderFundTransModelSerializer(many=True)
    discount_amount = serializers.SerializerMethodField(read_only=True)
    order_species_str = serializers.CharField(source='get_order_species_display', read_only=True)
    bill = serializers.SerializerMethodField(read_only=True)
    express_info = serializers.SerializerMethodField(read_only=True)
    orderaddress = serializers.SerializerMethodField(read_only=True)
    refundorderinfo_set = serializers.SerializerMethodField(read_only=True)
    after_sale = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)

    class Meta:
        model = OrderInfo
        fields = ['id', 'create_time', 'order_id', 'state_str', 'ordergoods_set', 'total_point', 'customer_user', 'companyuser',
                  'total_price', 'realpay_amount', 'discount_amount', 'orderfundtrans_set', 'state', 'use_time', 'orderNum', 'order_species', 'order_species_str',
                  'bill', 'express_info', 'orderaddress', 'refund_money', 'refundorderinfo_set', 'after_sale', 'freight', 'order_type', "order_type_str",
                  'payment_time']

    def get_after_sale(self, obj):
        try:
            after_sale = AfterSaleApplicationForm.objects.exclude(form_status=4).filter(order_id=obj.id).last()
            if after_sale:
                return AfterSaleApplicationFormModelSerializer(after_sale).data
            else:
                return {}
        except:
            return {}

    def get_refundorderinfo_set(self, obj):
        try:
            refundorderinfo_set = obj.refundorderinfo_set.all()
            return RefundOrderInfoModelSerializer(refundorderinfo_set, many=True).data
        except:
            return []

    def get_orderaddress(self, obj):
        try:
            orderaddress = obj.orderaddress
            if orderaddress:
                return OrderAddressModelSerializer(orderaddress).data
            else:
                return {}
        except:
            return {}

    def get_express_info(self, obj):
        try:
            express_id_list = ExpressOrderRelevance.objects.filter(order_id=obj.id).values_list('express_id', flat=True)
            express_set = Express.objects.filter(id__in=list(express_id_list))
            return ExpressModelSerializer(express_set, many=True).data
        except:
            return []

    def get_discount_amount(self, obj):
        try:
            if obj.state in [12, 2, 3, 9, 6, 8, 5, 14]:
                return str(Decimal(obj.total_price - obj.realpay_amount - obj.total_point/100).quantize(Decimal('0.00')))
            elif obj.state == 1:
                return str(Decimal(obj.total_price - obj.payable_amount - obj.total_point/100).quantize(Decimal('0.00')))
            else:
                return '0.00'
        except Exception as e:
            logger.error(e)
        return '0.00'

    def get_customer_user(self, obj):
        data = {}
        data['realname'] = ''
        data['level'] = ''
        data['mobile'] = ''
        data['id'] = ''
        data['merchant'] = []
        data['is_merchant'] = 0
        try:
            customer_user = obj.customer_user
            level = customer_user.level
            data['id'] = customer_user.id
            data['realname'] = customer_user.realname
            data['mobile'] = customer_user.mobile
            merchant_set = Merchant.objects.filter(managermobile=customer_user.mobile)
            if level:
                data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
            if merchant_set:
                data['is_merchant'] = 1
                merchant_list = []
                for merchant in merchant_set:
                    level = merchant.level
                    merchant_data = {}
                    merchant_data['id'] = merchant.id
                    merchant_data['business_no'] = merchant.wyfMerchantID
                    merchant_data['short_name'] = merchant.short_name
                    merchant_data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
                    merchant_list.append(merchant_data)
                data['merchant'] = merchant_list
            return data
        except Exception as e:
            pass
        return data

    def get_companyuser(self, obj):
        data = {}
        data['nickname'] = ''
        data['level'] = ''
        data['success_time'] = ''
        try:
            goodscoupons = obj.goodscoupons_set.all().order_by('-use_time').first()
            data['success_time'] = goodscoupons.use_time.strftime("%Y-%m-%d %H:%M:%S")
            companyuser = goodscoupons.use_user
            level = companyuser.level
            data['nickname'] = f'{companyuser.nickname}({companyuser.mobile})'
            data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
            return data
        except:
            pass
        return data

    def get_bill(self, obj):
        data = {}
        data['id'] = ''
        data['receipts_time'] = ''
        data['bill_state'] = ''
        data['bill_state_str'] = ''
        data['settlement_time'] = ''
        data['settlement_record_id'] = ''
        try:
            bill = obj.bill
            data['id'] = bill.id
            data['receipts_time'] = bill.receipts_time.strftime("%Y-%m-%d")
            data['bill_state'] = bill.bill_state
            data['bill_state_str'] = bill.get_bill_state_display()
            data['settlement_time'] = bill.settlement_time.strftime("%Y-%m-%d")
            data['settlement_record_id'] = bill.settlement_record_id
        except:
            pass
        return data


class ExpressTypeModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = ExpressType
        fields = ('id', 'express_type_name', 'logo')


class GoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    is_coupon_goods = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant', 'is_coupon_goods')

    def get_is_coupon_goods(self, obj):
        try:
            alidiscountcoupon_id = self.context.get('alidiscountcoupon_id', None)
            if alidiscountcoupon_id:
                check_available = AliDiscountCouponGoodsAvailable.objects.filter(goods_id=obj.id, alidiscountcoupon_id=alidiscountcoupon_id)
                if check_available:
                    return 1
                else:
                    return 0
            else:
                return 0
        except:
            return 0

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        data['name'] = ''
        data['short_name'] = ''
        data['id'] = ''
        try:
            merchant = obj.merchant
            data['name'] = merchant.name
            data['short_name'] = merchant.short_name
            data['id'] = merchant.id
        except:
            pass
        return data


class GoodsModifyApplymentModelSerializer(serializers.ModelSerializer):

    desc_detail = serializers.SerializerMethodField(read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    company_user = serializers.SerializerMethodField(read_only=True)
    applyment_type_str = serializers.CharField(source='get_applyment_type_display', read_only=True)

    class Meta:
        model = GoodsModifyApplyment
        fields = ('id', 'name', 'applyment_type', 'caption', 'desc_detail', 'price', 'market_price', 'default_image', 'goodsimage_set',
                  'manufacturer', 'specifications', 'applyment_type_str', 'company_user')

    def get_company_user(self, obj):
        try:
            return f'{obj.companyuser.nickname}({obj.companyuser.level.name})'
        except:
            return ''

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        try:
            return json.loads(obj.image_array)
        except:
            return obj.image_array


class GoodsRetrieveModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    category = serializers.SerializerMethodField(read_only=True)
    merchant_name = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)
    goodsimage_set = serializers.SerializerMethodField(read_only=True)
    desc_detail = serializers.SerializerMethodField(read_only=True)
    applyment = serializers.SerializerMethodField(read_only=True)
    reject_reason = serializers.SerializerMethodField(read_only=True)
    stock = serializers.SerializerMethodField(read_only=True)
    order_type_str = serializers.CharField(source='get_order_type_display', read_only=True)

    class Meta:
        model = Goods
        fields = ('id', 'create_time', 'equityID', 'category', 'name', 'default_image', 'is_launched', 'is_launched_str', 'price',
                  'sales', 'remain_stock', 'merchant_name', 'manufacturer', 'specifications', 'caption', 'goodsimage_set', 'desc_detail',
                  'market_price', 'merchant_id', 'applyment', 'reject_reason', 'goods_tag', 'order_type', 'order_type_str', 'stock')

    def get_stock(self, obj):
        try:
            launchedgoods = LaunchedGoods.objects.filter(goods_id=obj.id, is_self=1).first()
            if not launchedgoods:
                launched_goods_data = {}
                launched_goods_data['name'] = obj.name
                launched_goods_data['caption'] = obj.caption
                launched_goods_data['goods_id'] = obj.id
                launched_goods_data['category_id'] = obj.category_id
                launched_goods_data['price'] = obj.price
                launched_goods_data['point'] = obj.point
                launched_goods_data['stock'] = obj.stock
                launched_goods_data['is_launched'] = 0
                launched_goods_data['create_time'] = datetime.datetime.now()
                launched_goods_data['is_self'] = 1
                launchedgoods, create = LaunchedGoods.objects.get_or_create(defaults=launched_goods_data, goods_id=obj.id, is_self=1)
            return launchedgoods.stock
        except:
            pass
        return 0

    def get_reject_reason(self, obj):
        try:
            if obj.is_launched == 3:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=3).last()
                return applyment.reject_reason
            else:
                return ''
        except:
            return ''

    def get_applyment(self, obj):
        try:
            if obj.is_launched == 2:
                applyment = obj.goodsmodifyapplyment_set.all().filter(applyment_status=1).first()
                return GoodsModifyApplymentModelSerializer(applyment).data
            else:
                return {}
        except:
            return {}

    def get_desc_detail(self, obj):
        try:
            return json.loads(obj.desc_detail.replace("'", '"'))
        except:
            return obj.desc_detail

    def get_goodsimage_set(self, obj):
        data = []
        try:
            goodsimage_set = obj.goodsimage_set.all()
            for goodsimage in goodsimage_set:
                data.append(goodsimage.image.url)
        except:
            pass
        return data

    def get_category(self, obj):
        try:
            return obj.category.name
        except:
            return ''

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''


class GoodsCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = ['id', 'name', 'icon']


class MerchantBusinessCategoryModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = MerchantBusinessCategory
        fields = ['id', 'name']


class MerchantBillListModelSerializer(serializers.ModelSerializer):

    receipts_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    bill_state_str = serializers.CharField(source='get_bill_state_display', read_only=True)
    bill_type_str = serializers.CharField(source='get_bill_type_display', read_only=True)
    merchant_info = serializers.SerializerMethodField(read_only=True)
    account_info = serializers.SerializerMethodField(read_only=True)
    week_day = serializers.SerializerMethodField(read_only=True)
    order_count = serializers.SerializerMethodField(read_only=True)
    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    channel_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBill
        fields = ['id', 'receipts_time', 'bill_state', 'bill_state_str', 'merchant_info', 'payable_amount', 'account_info', 'settlement_time', 'week_day',
                  'order_count', 'channel_id', 'channel_name', 'bill_type', 'bill_type_str']

    def get_channel_name(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_order_count(self, obj):
        try:
            return obj.orderinfo_set.all().count()
        except:
            return 0

    def get_week_day(self, obj):
        week_day_dict = {
            0: '星期一',
            1: '星期二',
            2: '星期三',
            3: '星期四',
            4: '星期五',
            5: '星期六',
            6: '星期日',
        }
        day = obj.receipts_time.weekday()
        return week_day_dict[day]

    def get_merchant_info(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['wyfMerchantID'] = ''
        data['level_name'] = ''
        data['district_name'] = ''
        data['branch_name'] = ''
        data['merchant_id'] = ''
        try:
            merchant = obj.merchant
            level = merchant.level
            data['merchant_name'] = merchant.name
            data['wyfMerchantID'] = merchant.wyfMerchantID
            data['level_name'] = level.name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            data['merchant_id'] = merchant.id
        except:
            pass
        return data

    def get_account_info(self, obj):
        data = {}
        data['account_number'] = ''
        data['account_bank'] = ''
        data['account_name'] = ''
        try:
            bill_state = obj.bill_state
            if bill_state == 1:
                data['account_number'] = str(obj.merchant.account_number)[:6] + '********' + str(obj.merchant.account_number)[-5:]
                data['account_bank'] = obj.merchant.account_bank
                data['account_name'] = obj.merchant.account_name
            else:
                data['account_number'] = obj.account_number
                data['account_bank'] = obj.account_bank
                data['account_name'] = obj.account_name
        except:
            pass
        return data


class MerchantBillRetrieveModelSerializer(serializers.ModelSerializer):

    receipts_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    bill_state_str = serializers.CharField(source='get_bill_state_display', read_only=True)
    merchant_info = serializers.SerializerMethodField(read_only=True)
    order_count = serializers.SerializerMethodField(read_only=True)
    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    account_info = serializers.SerializerMethodField(read_only=True)
    # payable_amount = serializers.SerializerMethodField(read_only=True)
    settlement_info = serializers.SerializerMethodField(read_only=True)
    fail_reason = serializers.SerializerMethodField(read_only=True)
    bill_type_str = serializers.CharField(source='get_bill_type_display', read_only=True)
    other_amount = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MerchantBill
        fields = ['id', 'receipts_time', 'bill_state', 'bill_state_str', 'merchant_info', 'payable_amount', 'settlement_time', 'order_count', 'account_info',
                  'settlement_info', 'fail_reason', 'bill_type', 'bill_type_str', 'commission', 'amount', 'other_amount', 'other_commission', 'other_settlement_amount']

    def get_other_amount(self, obj):
        try:
            yesterday = datetime.datetime.now() + datetime.timedelta(days=-1)
            if obj.other_amount == None and obj.receipts_time < yesterday:
                url = 'https://manage.gdwxyf.com/internal/searchorders.do'
                body = {
                    "shopId": obj.merchant.wyfMerchantID,
                    "start": obj.receipts_time.strftime("%Y-%m-%d 00:00:00"),
                    "end": obj.receipts_time.strftime("%Y-%m-%d 23:59:59"),
                    "branchId": "2",
                    "account": "gdyouzheng",
                    "orderStatus": "all"
                }
                response = requests.post(url=url, data=body)
                result = response.json()['showList']
                other_amount = Decimal('0')
                other_commission = Decimal('0')
                other_settlement_amount = Decimal('0')
                for i in result:
                    if 'subOpenid' in i:
                        if 'omjwf4' != i['subOpenid'][:6]:
                            other_amount += Decimal(i['totalFee'])
                            other_commission += Decimal(i['commissionPay'])
                            other_settlement_amount += Decimal(i['paidout'])
                    else:
                        if i['device'] != '微邮惠商圈':
                            other_amount += Decimal(i['totalFee'])
                            other_commission += Decimal(i['commissionPay'])
                            other_settlement_amount += Decimal(i['paidout'])
                obj.other_amount = other_amount
                obj.other_commission = other_commission
                obj.other_settlement_amount = other_settlement_amount
                obj.save()
                return obj.other_amount
            else:
                return obj.other_amount
        except:
            return ''

    def get_fail_reason(self, obj):
        return ''

    def get_settlement_info(self, obj):
        data = []
        try:
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                merchantsettlementrecord_data = {}
                merchantsettlementrecord = merchantbillsettlementrecord.settlement_record
                merchantsettlementrecord_data['settlement_time'] = merchantsettlementrecord.settlement_time.strftime('%Y-%m-%d')
                merchantsettlementrecord_data['settlement_id'] = merchantsettlementrecord.id
                merchantsettlementrecord_data['settlement_amount'] = merchantsettlementrecord.amount
                merchantsettlementrecord_data['status'] = merchantsettlementrecord.status
                merchantsettlementrecord_data['status_str'] = merchantsettlementrecord.get_status_display()
                data.append(merchantsettlementrecord_data)
        except:
            pass
        return data

    # def get_payable_amount(self, obj):
    #     try:
    #         bill_state = obj.bill_state
    #         if bill_state == 3:
    #             return obj.settlement_record.amount
    #         else:
    #             return 0
    #     except:
    #         return 0

    def get_merchant_info(self, obj):
        data = {}
        data['merchant_name'] = ''
        data['wyfMerchantID'] = ''
        data['level'] = ''
        data['merchant_id'] = ''
        try:
            data['merchant_name'] = obj.merchant.name
            data['wyfMerchantID'] = obj.merchant.wyfMerchantID
            data['merchant_id'] = obj.merchant_id
            level = obj.merchant.level
            data['level'] = f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
        except:
            pass
        return data

    def get_order_count(self, obj):
        try:
            return obj.orderinfo_set.all().count()
        except:
            return 0

    def get_account_info(self, obj):
        data = {}
        data['account_number'] = ''
        data['account_bank'] = ''
        data['account_name'] = ''
        try:
            bill_state = obj.bill_state
            if bill_state == 1:
                data['account_number'] = str(obj.merchant.account_number)[:6] + '********' + str(obj.merchant.account_number)[-5:]
                data['account_bank'] = obj.merchant.account_bank
                data['account_name'] = obj.merchant.account_name
            else:
                data['account_number'] = obj.account_number
                data['account_bank'] = obj.account_bank
                data['account_name'] = obj.account_name
        except:
            pass
        return data


class MerchantSettlementRecordListModelSerializer(serializers.ModelSerializer):

    settlement_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    channel = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    receipts_time = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)

    class Meta:
        model = MerchantSettlementRecord
        fields = ['id', 'settlement_time', 'channel', 'channel_id', 'status', 'status_str', 'amount', 'receipts_time', 'merchant', 'level_name', 'is_bind',
                  'is_bind_str']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = obj.merchant
            data['merchant_name'] = merchant.name
            data['merchant_id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
        except:
            pass
        return data

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_receipts_time(self, obj):
        data = ''
        try:
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                data += f"{merchantbillsettlementrecord.bill.receipts_time.strftime('%Y-%m-%d')},"
        except:
            pass
        if ',' in data:
            data = data[:-1]
        return data


class MerchantSettlementRecordRetrieveModelSerializer(serializers.ModelSerializer):

    settlement_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    channel = serializers.SerializerMethodField(read_only=True)
    status_str = serializers.CharField(source='get_status_display', read_only=True)
    receipts_data = serializers.SerializerMethodField(read_only=True)
    merchant = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_bind_str = serializers.CharField(source='get_is_bind_display', read_only=True)

    class Meta:
        model = MerchantSettlementRecord
        fields = ['id', 'settlement_time', 'channel', 'channel_id', 'status', 'status_str', 'amount', 'receipts_data', 'merchant', 'level_name',
                  'account_name', 'account_bank', 'account_number', 'fail_reason', 'is_bind', 'is_bind_str']

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''

    def get_merchant(self, obj):
        data = {}
        try:
            merchant = obj.merchant
            level = merchant.level
            data['merchant_name'] = merchant.name
            data['merchant_id'] = merchant.id
            data['business_no'] = merchant.wyfMerchantID
            data['level'] =  f'{level.prov_name}-{level.city_name}-{level.district_name}-{level.branch_name}'.replace('None', '')
        except:
            pass
        return data

    def get_channel(self, obj):
        try:
            return obj.channel.name
        except:
            return ''

    def get_receipts_data(self, obj):
        data = {}
        try:
            bill_list = []
            time_str = ''
            order_num = 0
            merchantbillsettlementrecord_set = obj.merchantbillsettlementrecord_set.all()
            for merchantbillsettlementrecord in merchantbillsettlementrecord_set:
                bill_data = {}
                bill = merchantbillsettlementrecord.bill
                receipts_time = bill.receipts_time.strftime('%Y-%m-%d')
                time_str += f"{receipts_time},"
                orderinfo_set = bill.orderinfo_set.all()
                if orderinfo_set:
                    order_sum = orderinfo_set.count()
                    payable_settled_amount__sum = orderinfo_set.aggregate(Sum('payable_settled_amount'))['payable_settled_amount__sum']
                    order_num += order_sum
                    bill_data['order_count'] = order_sum
                    bill_data['payable_settled_amount__sum'] = payable_settled_amount__sum
                    bill_data['receipts_time'] = receipts_time
                    bill_data['bill_id'] = bill.id
                    bill_list.append(bill_data)
            if ',' in time_str:
                time_str = time_str[:-1]
            data['receipts_time'] = time_str
            data['order_count'] = order_num
            data['array'] = bill_list
        except:
            pass
        return data


class MerchantMonthlyBillListModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model =  MerchantMonthlyBill
        fields = ('id', 'bill_name', 'bill_time', 'order_amount', 'order_count', 'separate_amount', 'restitution_amount', 'merchant', 'settlement_amount',
                  'merchant_id', 'merchant_name', 'level_name')

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_level_name(self, obj):
        try:
            return obj.level.name
        except:
            return ''


class MerchantMonthlyBillRetrieveModelSerializer(serializers.ModelSerializer):

    merchant_name = serializers.SerializerMethodField(read_only=True)
    level = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model =  MerchantMonthlyBill
        fields = ('id', 'bill_name', 'bill_time', 'order_amount', 'order_count', 'separate_amount', 'restitution_amount',
                  'settlement_amount', 'bill_file', 'merchant_id', 'merchant_name', 'level')

    def get_merchant_name(self, obj):
        try:
            return obj.merchant.name
        except:
            return ''

    def get_level(self, obj):
        data = {
            'prov_name': '',
            'city_name': '',
            'district_name': '',
            'branch_name': ''
        }
        try:
            level = obj.level
            data['prov_name'] = level.prov_name
            data['city_name'] = level.city_name
            data['district_name'] = level.district_name
            data['branch_name'] = level.branch_name
            return data
        except:
            return data


class LaunchedGoodsListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    goodsinfo = serializers.SerializerMethodField(read_only=True)
    level_name = serializers.SerializerMethodField(read_only=True)
    is_launched_str = serializers.CharField(source='get_is_launched_display', read_only=True)

    class Meta:
        model = LaunchedGoods
        fields = ('id', 'create_time', 'point', 'goodsinfo', 'sales', 'level_name', 'is_launched', 'is_launched_str', 'stock', 'is_self')

    def get_goodsinfo(self, obj):
        data = {}
        data['default_image'] = ''
        data['name'] = ''
        data['category'] = ''
        data['equityID'] = ''
        data['merchant_name'] = ''
        data['sales'] = ''
        data['remain_stock'] = ''
        try:
            goods = obj.goods
            data['default_image'] = goods.default_image.url
            data['name'] = goods.name
            data['category'] = goods.category.name
            data['equityID'] = goods.equityID
            data['merchant_name'] = goods.merchant.name
            data['sales'] = goods.sales
            data['remain_stock'] = goods.remain_stock
        except:
            pass
        return data

    def get_level_name(self, obj):
        try:
            if obj.is_self == 0:
                return obj.level.name
            else:
                return '自营'
        except:
            return ''


class AfterSaleApplicationFormListModelSerializer(serializers.ModelSerializer):

    form_status_str = serializers.CharField(source='get_form_status_display', read_only=True)
    reason_type_str = serializers.CharField(source='get_reason_type_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    img_array = serializers.SerializerMethodField(read_only=True)
    reason = serializers.SerializerMethodField(read_only=True)
    order = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AfterSaleApplicationForm
        fields = ['id', 'form_status', 'form_status_str', 'create_time', 'description', 'refund_money', 'return_msg', 'refund_time', 'reason', 'img_array',
                  'application_num', 'order', 'reason_type_str', 'reason_type']

    def get_order(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        data['order_id'] = ''
        data['default_image'] = ''
        data['goods_name'] = ''
        try:
            order = obj.order
            order_goods = OrderGoods.objects.filter(order_id=order.id).first()
            goods = order_goods.goods
            data['id'] = order.id
            data['merchant_name'] = order.merchant.name
            data['order_id'] = order.orderNum
            data['default_image'] = goods.default_image.url
            data['goods_name'] = goods.name
        finally:
            return data

    def get_reason(self, obj):
        try:
            return obj.reason.name
        except:
            return ''

    def get_img_array(self, obj):
        data = []
        try:
            queryset = AfterSaleApplicationFormImg.objects.filter(applicationform_id=obj.id)
            for query in queryset:
                data.append(query.img.url)
        except:
            pass
        return data


class AfterSaleApplicationFormRetrieveModelSerializer(serializers.ModelSerializer):

    form_status_str = serializers.CharField(source='get_form_status_display', read_only=True)
    reason_type_str = serializers.CharField(source='get_reason_type_display', read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    refund_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    img_array = serializers.SerializerMethodField(read_only=True)
    reason = serializers.SerializerMethodField(read_only=True)
    order = serializers.SerializerMethodField(read_only=True)
    orderaddress = serializers.SerializerMethodField(read_only=True)
    number = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = AfterSaleApplicationForm
        fields = ['id', 'form_status', 'form_status_str', 'create_time', 'description', 'refund_money', 'return_msg', 'refund_time', 'reason', 'img_array',
                  'application_num', 'order', 'orderaddress', 'reason_type', 'reason_type_str', 'number']

    def get_number(self, obj):
        return 1

    def get_order(self, obj):
        data = {}
        data['id'] = ''
        data['merchant_name'] = ''
        data['default_image'] = ''
        data['total_price'] = ''
        data['goods_name'] = ''
        try:
            order = obj.order
            order_goods = OrderGoods.objects.filter(order_id=order.id).first()
            data['id'] = order.id
            data['merchant_name'] = order.merchant.name
            data['default_image'] = order_goods.goods.default_image.url
            data['total_price'] = order.total_price
            data['goods_name'] = order_goods.goods.name
        finally:
            return data

    def get_reason(self, obj):
        try:
            return obj.reason.name
        except:
            return ''

    def get_img_array(self, obj):
        data = []
        try:
            queryset = AfterSaleApplicationFormImg.objects.filter(applicationform_id=obj.id)
            for query in queryset:
                data.append(query.img.url)
        except:
            pass
        return data

    def get_orderaddress(self, obj):
        data = {}
        data['receiver'] = ''
        data['place'] = ''
        data['mobile'] = ''
        try:
            merchant = obj.order.merchant
            data['receiver'] = merchant.managerName
            data['place'] = merchant.store_address
            data['mobile'] = merchant.managermobile
        finally:
            return data


class OrderGoodsCommentFileModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = OrderGoodsCommentFile
        fields = ('id', 'file', 'file_type')


class GoodsCommentModelSerializer(serializers.ModelSerializer):

    ordergoodscommentfile_set = OrderGoodsCommentFileModelSerializer(many=True)
    comment_time = serializers.DateTimeField(format="%Y-%m-%d", required=False)
    username = serializers.SerializerMethodField(read_only=True)
    avatar = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ('id', 'is_commented', 'comment', 'ordergoodscommentfile_set',
                  'comment_time', 'is_anonymous', 'avatar', 'username')

    def get_username(self, obj):
        try:
            if obj.is_anonymous == 1:
                return '匿名买家'
            else:
                return obj.order.customeruservice.username
        except:
            return '匿名买家'

    def get_avatar(self, obj):
        try:
            if obj.is_anonymous == 1:
                return 'https://jinjian.sutpay.cn/image/wyh_img101.png'
            else:
                return obj.order.customeruservice.avatar
        except:
            return 'https://jinjian.sutpay.cn/image/wyh_img101.png'


class ExpressListModelSerializer(serializers.ModelSerializer):

    express_type = serializers.SerializerMethodField(read_only=True)
    express_type_logo = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'express_type_id', 'express_type', 'express_type_logo', 'express_number', 'create_time', 'sign_time',
                  'deliverystatus', 'deliverystatus_str')

    def get_express_type(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''

    def get_express_type_logo(self, obj):
        try:
            return obj.express_type.logo
        except:
            return ''


class ExpressRetrieveModelSerializer(serializers.ModelSerializer):

    express_type = serializers.SerializerMethodField(read_only=True)
    express_type_logo = serializers.SerializerMethodField(read_only=True)
    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    sign_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    deliverystatus_str = serializers.CharField(source='get_deliverystatus_display', read_only=True)
    expressplan_set = serializers.SerializerMethodField(read_only=True)
    order_set = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Express
        fields = ('id', 'express_type_id', 'express_type', 'express_type_logo', 'express_number', 'create_time', 'sign_time',
                  'deliverystatus', 'deliverystatus_str', 'expressplan_set', 'order_set')

    def get_order_set(self, obj):
        try:
            order_id_list = obj.expressorderrelevance_set.all().values_list('order_id', flat=True)
            order_set = OrderInfo.objects.filter(id__in=list(order_id_list))
            return OrderInfoListModelSerializer(order_set, many=True).data
        except:
            return []

    def get_expressplan_set(self, obj):
        try:
            expressplan_set = obj.expressplan_set.all().order_by('-create_time')
            return ExpressPlanModelSerializer(expressplan_set, many=True).data
        except:
            return []

    def get_express_type(self, obj):
        try:
            return obj.express_type.express_type_name
        except:
            return ''

    def get_express_type_logo(self, obj):
        try:
            return obj.express_type.logo
        except:
            return ''


class ExpressQuestListModelSerializer(serializers.ModelSerializer):

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)
    is_enter_str = serializers.CharField(source='get_is_enter_display', read_only=True)
    user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = ExpressQuest
        fields = ('id', 'create_time', 'file', 'logs_file', 'is_enter_str', 'is_enter', 'line_number', 'success_number', 'error_number', 'user')

    def get_user(self, obj):
        try:
            return obj.user.nickname
        except:
            return ''